package main

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

var db *gorm.DB
var err error

type adminInfo struct {
	gorm.Model
	Adminid   string
	Password  string
	Key       string
	Adminname string
	Limit     string
}

// User 用户数据
type User struct {
	gorm.Model
	UserName     string
	UserPassword string
	Key          string
	Devices      []Device
}

// Device 设备数据
type Device struct {
	gorm.Model
	DeviceID      string
	DevicesName   string
	DevicesStatus string
	UserID        uint
	DeviceInfo    string
}

func migrate() (bool, error) {
	isMigrate := false
	if isMigrate == false {
		return isMigrate, nil
	}

	db.AutoMigrate(&adminInfo{})
	db.AutoMigrate(&User{})
	db.AutoMigrate(&Device{})

	// user := User{UserName: "测试2", UserPassword: "123456", Key: "10003", Devices: []Device{
	// 	{DeviceID: "lock1011", DevicesName: "智能锁", DevicesStatus: "离线"},
	// },
	// }
	// db.Create(&user)
	// device := Device{DeviceID: "lock1010", DevicesName: "智能锁", DevicesStatus: "离线", UserID: user.Model.ID}
	// db.Create(&device)
	var user User
	var devices []Device
	if err = db.First(&user, "user_name = ?", "杨华文").Error; err != nil {
		fmt.Println(err)
	}
	db.Model(&user).Related(&devices, "Devices")
	fmt.Println(user.Key)
	// db.Create(&adminInfo{Adminid: "admin1", Adminname: "测试", Password: "123456", Key: "admin", Limit: "超级管理员"})
	// var users []adminInfo
	// err := db.Find(&users).Error
	// for _, info := range users {
	// 	fmt.Println(info.Adminname)
	// }

	return isMigrate, err
}
